package com.lin.pan.server.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.pan.cache.core.constants.CacheConstants;
import com.lin.pan.core.exception.RPanBusinessException;
import com.lin.pan.core.response.ResponseCode;
import com.lin.pan.core.utils.IdUtil;
import com.lin.pan.core.utils.JwtUtil;
import com.lin.pan.core.utils.PasswordUtil;
import com.lin.pan.server.modules.file.constants.FileConstants;
import com.lin.pan.server.modules.file.context.CreateFolderContext;
import com.lin.pan.server.modules.file.entity.RPanUserFile;
import com.lin.pan.server.modules.file.service.IUserFileService;
import com.lin.pan.server.modules.user.Vo.UserInfoVO;
import com.lin.pan.server.modules.user.constants.UserConstants;
import com.lin.pan.server.modules.user.context.*;
import com.lin.pan.server.modules.user.converter.UserConverter;
import com.lin.pan.server.modules.user.entity.RPanUser;
import com.lin.pan.server.modules.user.service.IUserService;
import com.lin.pan.server.modules.user.mapper.RPanUserMapper;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author jeremylin
 * @description 针对表【r_pan_user(用户信息表)】的数据库操作Service实现
 * @createDate 2023-10-19 10:33:40
 */
@Service
public class UserServiceImpl extends ServiceImpl<RPanUserMapper, RPanUser>
        implements IUserService {

    @Autowired
    private UserConverter userConverter;

    @Autowired
    private IUserFileService iUserFileService;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 用户注册的业务实现
     * 需要实现的功能点：
     * 1、注册用户信息
     * 2、创建新用户的根本目录信息
     * <p>
     * 需要实现的技术难点：
     * 1、该业务是幂等的
     * 2、要保证用户名全局唯一
     * <p>
     * 实现技术难点的处理方案：
     * 1、幂等性通过数据库表对于用户名字段添加唯一索引，我们上有业务捕获对应的冲突异常，转化返回
     *
     * @param userRegisterContext
     * @return
     */
    @Override
    public Long register(UserRegisterContext userRegisterContext) {
        assembleUserEntity(userRegisterContext);
        doRegister(userRegisterContext);
        createUserRootFolder(userRegisterContext);
        return userRegisterContext.getEntity().getUserId();
    }

    /**
     * 用户登录业务实现
     * <p>
     * 需要实现的功能：
     * 1、用户的登录信息校验
     * 2、生成一个具有时效性的accessToken
     * 3、将accessToken缓存起来，去实现单机登录
     *
     * @param userLoginContext
     * @return
     */
    @Override
    public String login(UserLoginContext userLoginContext) {
        checkLoginInfo(userLoginContext);
        generateAndSaveAccessToken(userLoginContext);
        return userLoginContext.getAccessToken();
    }

    /**
     * 用户退出登录
     * <p>
     * 1、清除用户的登录凭证缓存
     *
     * @param userId
     */
    @Override
    public void exit(Long userId) {
        try {
            Cache cache = cacheManager.getCache(CacheConstants.R_PAN_CACHE_NAME);
            cache.evict(UserConstants.USER_LOGIN_PREFIX + userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RPanBusinessException("用户退出登录失败");
        }
    }

    /**
     * 用户忘记密码-校验用户名称
     *
     * @param checkUsernameContext
     * @return
     */
    @Override
    public String checkUsername(CheckUsernameContext checkUsernameContext) {
        String question = baseMapper.selectQuestionByUsername(checkUsernameContext.getUsername());
        if (StringUtil.isNullOrEmpty(question)) {
            throw new RPanBusinessException("用户名不存在");
        }
        return question;
    }

    /**
     * 用户忘记密码-校验密保
     *
     * @param checkAnswerContext
     * @return
     */
    @Override
    public String checkAnswer(CheckAnswerContext checkAnswerContext) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", checkAnswerContext.getUsername());
        queryWrapper.eq("question", checkAnswerContext.getQuestion());
        queryWrapper.eq("answer", checkAnswerContext.getAnswer());

        int count = count(queryWrapper);
        if (count == 0) {
            throw new RPanBusinessException("密保问题错误");
        }

        return generateCheckAnswerToken(checkAnswerContext);
    }

    /**
     * 用户忘记密码-重置密码
     * 1、校验token是不是有效
     * 2、重置密码
     *
     * @param resetPasswordContext
     * @return
     */
    public void resetPassword(ResetPasswordContext resetPasswordContext) {
        checkForgetPasswordToken(resetPasswordContext);
        checkAndResetPassword(resetPasswordContext);
    }

    /**
     * 在线修改密码
     * 1、校验旧密码
     * 2、重置新密码
     * 3、退出当前的登录状态
     *
     * @param changePasswordContext
     */
    public void changePassword(ChangePasswordContext changePasswordContext) {
        checkOldPassword(changePasswordContext);
        doChangePassword(changePasswordContext);
        exitLoginStatus(changePasswordContext);
    }

    /**
     * 查询在线用户的基本信息
     * 1、查询用户的基本信息实体
     * 2、查询用户的根文件夹信息
     * 3、拼装VO对象返回
     *
     * @param userId
     * @return
     */
    public UserInfoVO info(Long userId) {
        RPanUser user = getById(userId);
        if (Objects.isNull(user)) {
            throw new RPanBusinessException("用户信息不存在");
        }

        RPanUserFile userFile = getUserRootFileInfo(userId);
        if (Objects.isNull(userFile)) {
            throw new RPanBusinessException("用户根目录不存在");
        }
        UserInfoVO userInfoVO = userConverter.assembleUserInfoVO(user, userFile);
        return userInfoVO;
    }

    /**
     * 获取用户根文件夹信息实体
     *
     * @param userId
     * @return
     */
    private RPanUserFile getUserRootFileInfo(Long userId) {
        return iUserFileService.getUserRootFile(userId);
    }

    /**
     * 退出用户登录状态
     *
     * @param changePasswordContext
     */
    private void exitLoginStatus(ChangePasswordContext changePasswordContext) {
        Long userId = changePasswordContext.getUserId();
        exit(userId);
    }

    /**
     * 修改新密码
     *
     * @param changePasswordContext
     */
    private void doChangePassword(ChangePasswordContext changePasswordContext) {
        String newPassword = changePasswordContext.getNewPassword();
        RPanUser entity = changePasswordContext.getEntity();
        String salt = entity.getSalt();
        String encNewPassword = PasswordUtil.encryptPassword(salt, newPassword);
        entity.setPassword(encNewPassword);
        if (!updateById(entity)) {
            throw new RPanBusinessException("修改密码失败");
        }
    }

    /**
     * 校验用户的旧密码
     * 该步骤会查询并封装用户的实体信息到上下文对象中
     *
     * @param changePasswordContext
     */
    private void checkOldPassword(ChangePasswordContext changePasswordContext) {
        Long userId = changePasswordContext.getUserId();
        String oldPassword = changePasswordContext.getOldPassword();

        RPanUser user = getById(userId);
        if (Objects.isNull(user)) {
            throw new RPanBusinessException("用户信息不存在");
        }
        changePasswordContext.setEntity(user);

        String encOldPassword = PasswordUtil.encryptPassword(user.getSalt(), oldPassword);
        String dbPassword = user.getPassword();
        if (!encOldPassword.equals(dbPassword)) {
            throw new RPanBusinessException("旧密码错误");
        }
    }


    /***************************************************************private***************************************************************/

    /**
     * 校验用户信息并重置用户密码
     *
     * @param resetPasswordContext
     */
    private void checkAndResetPassword(ResetPasswordContext resetPasswordContext) {
        String username = resetPasswordContext.getUsername();
        String password = resetPasswordContext.getPassword();

        RPanUser user = getRPanUserByUsername(username);
        if (Objects.isNull(user)) {
            throw new RPanBusinessException("用户信息不存在");
        }
        String newPassword = PasswordUtil.encryptPassword(user.getSalt(), password);
        user.setPassword(newPassword);
        user.setUpdateTime(new Date());

        if (!updateById(user)) {
            throw new RPanBusinessException("重置密码失败");
        }
    }

    /**
     * 用户忘记密码 - 校验token是不是有效
     *
     * @param resetPasswordContext
     */
    private void checkForgetPasswordToken(ResetPasswordContext resetPasswordContext) {
        String token = resetPasswordContext.getToken();
        Object value = JwtUtil.analyzeToken(token, UserConstants.FORGET_USERNAME);
        if (Objects.isNull(value)) {
            throw new RPanBusinessException(ResponseCode.TOKEN_EXPIRE);
        }

        String username = value.toString();
        if (!Objects.equals(username, resetPasswordContext.getUsername())) {
            throw new RPanBusinessException("token错误");
        }
    }

    /**
     * 生成密保token
     * token的失效时间为五分钟之后
     *
     * @param checkAnswerContext
     * @return
     */
    private String generateCheckAnswerToken(CheckAnswerContext checkAnswerContext) {
        String token = JwtUtil.generateToken(checkAnswerContext.getUsername(), UserConstants.FORGET_USERNAME, checkAnswerContext.getUsername(), UserConstants.FIVE_MINUTES_LONG);
        return token;
    }

    /**
     * 生成并保存登陆之后的凭证
     *
     * @param userLoginContext
     */
    private void generateAndSaveAccessToken(UserLoginContext userLoginContext) {
        RPanUser user = userLoginContext.getEntity();
        String accessToken = JwtUtil.generateToken(user.getUsername(), UserConstants.LOGIN_USER_ID, user.getUserId(), UserConstants.ONE_DAY_LONG);

        Cache cache = cacheManager.getCache(CacheConstants.R_PAN_CACHE_NAME);
        cache.put(UserConstants.USER_LOGIN_PREFIX + user.getUserId(), accessToken);

        userLoginContext.setAccessToken(accessToken);
    }

    /**
     * 校验用户名密码
     *
     * @param userLoginContext
     */

    private void checkLoginInfo(UserLoginContext userLoginContext) {
        String username = userLoginContext.getUsername();
        String password = userLoginContext.getPassword();

        RPanUser user = getRPanUserByUsername(username);
        if (Objects.isNull(user)) {
            throw new RPanBusinessException("用户不存在");
        }
        // 对比密码
        String salt = user.getSalt();
        String encPassword = PasswordUtil.encryptPassword(salt, password);
        String dbPassword = user.getPassword();
        if (!Objects.equals(encPassword, dbPassword)) {
            throw new RPanBusinessException("密码错误");
        }
        userLoginContext.setEntity(user);
    }

    /**
     * 通过用户名称获取用户实体信息
     *
     * @param username
     * @return
     */
    private RPanUser getRPanUserByUsername(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);

        return getOne(queryWrapper);
    }

    /**
     * 实体转化
     * 由上下文信息转化成用户实体，封装进上下文
     *
     * @param userRegisterContext
     */
    private void assembleUserEntity(UserRegisterContext userRegisterContext) {
        RPanUser entity = userConverter.userRegisterContext2RPanUser(userRegisterContext);
        String salt = PasswordUtil.getSalt(),
                dbPassword = PasswordUtil.encryptPassword(salt, userRegisterContext.getPassword());
        entity.setUserId(IdUtil.get());
        entity.setSalt(salt);
        entity.setPassword(dbPassword);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        userRegisterContext.setEntity(entity);
    }


    /**
     * 实现注册用户的业务
     * 需要捕获数据库的唯一索引冲突异常，来实现全局用户名称唯一
     *
     * @param userRegisterContext
     */
    private void doRegister(UserRegisterContext userRegisterContext) {
        RPanUser entity = userRegisterContext.getEntity();
        if (Objects.nonNull(entity)) {
            try {
                if (!save(entity)) {
                    throw new RPanBusinessException("用户注册失败");
                }
            } catch (DuplicateKeyException duplicateKeyException) {
                // 对象唯一索引冲突，用户名已存在
                throw new RPanBusinessException("用户名已存在");
            }
            return;
        }
        throw new RPanBusinessException(ResponseCode.ERROR);
    }

    /**
     * 创建用户的根目录信息
     *
     * @param userRegisterContext
     * @return
     */
    private void createUserRootFolder(UserRegisterContext userRegisterContext) {
        CreateFolderContext createFolderContext = new CreateFolderContext();
        createFolderContext.setParentId(FileConstants.TOP_PARENT_ID);
        createFolderContext.setUserId(userRegisterContext.getEntity().getUserId());
        createFolderContext.setFolderName(FileConstants.ALL_FILE_CN_STR);
        iUserFileService.createFolder(createFolderContext);
    }

}




